package com.tacc.tyun.common.httpclient;

import org.apache.http.conn.HttpClientConnectionManager;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * 定期关闭无效连接
 * @author taocongcong
 * @create 2017-07-11 14:32
 */
public class IdleConnectionEvictor extends Thread {

    @Autowired
    private PoolingHttpClientConnectionManager poolingHttpClientConnectionManager;

    private volatile boolean shutdown;

    public IdleConnectionEvictor(PoolingHttpClientConnectionManager poolingHttpClientConnectionManager) {
        this.poolingHttpClientConnectionManager = poolingHttpClientConnectionManager;
        //启动当前线程
        this.start();
    }

    @Override
    public void run() {
        try {
            while (!shutdown) {
                synchronized (this) {
                    wait(1000);
                    // 关闭失效的连接
                    poolingHttpClientConnectionManager.closeExpiredConnections();
                }
            }
        } catch (InterruptedException ex) {
            // 结束
        }
    }

    public void shutdown() {
        shutdown = true;
        synchronized (this) {
            notifyAll();
        }
    }
}
